package vip.liux.backend.application.serviceImpl.gen;

import org.springframework.stereotype.Service;
import vip.liux.application.dots.ListResultDto;
import vip.liux.application.dots.PagedResultDto;
import vip.liux.application.dots.PagedResultRequestDto;
import vip.liux.backend.application.service.gen.GenDataSourceService;
import vip.liux.backend.domain.models.gen.GenDataSource;
import vip.liux.backend.infrastructure.jpa.gen.GenDataSourceMapper;

import static vip.liux.application.PageKit.toPage;
import static vip.liux.application.PageKit.toPaged;

@Service
public class GenDataSourceServiceImpl implements GenDataSourceService {

    private final GenDataSourceMapper dataSourceMapper;

    public GenDataSourceServiceImpl(GenDataSourceMapper dataSourceMapper) {
        this.dataSourceMapper = dataSourceMapper;
    }

    @Override
    public PagedResultDto<GenDataSource> pageList(PagedResultRequestDto input) {
        return toPaged(dataSourceMapper.findAll(toPage(input)));
    }

    @Override
    public GenDataSource detail(Long id) {
        return dataSourceMapper.findById(id).orElseThrow(() -> new RuntimeException("Data source not found with id: " + id));
    }

    @Override
    public GenDataSource save(GenDataSource dataSource) {
        return dataSourceMapper.save(dataSource);
    }

    @Override
    public void delete(Long id) {
        dataSourceMapper.deleteById(id);
    }

    @Override
    public ListResultDto<GenDataSource> list() {
        return new ListResultDto<>(dataSourceMapper.findAll());
    }

    @Override
    public GenDataSource update(Long id, GenDataSource input) {
        GenDataSource existingDataSource = dataSourceMapper.findById(id)
                .orElseThrow(() -> new RuntimeException("Data source not found with id: " + id));
        existingDataSource.setDefaultDataSource(input.getDefaultDataSource());
        existingDataSource.setDbType(input.getDbType());
        existingDataSource.setType(input.getType());
        existingDataSource.setName(input.getName());
        existingDataSource.setUrl(input.getUrl());
        existingDataSource.setUsername(input.getUsername());
        existingDataSource.setPassword(input.getPassword());
        return dataSourceMapper.save(existingDataSource);
    }
}




